package com.aws.one;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.TransferProgress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2024/1/15 - 15:42
 */
@Component
@Slf4j
public class DownLoadTest {
    @Autowired
    AmazonS3 amazonS3;
    String  downloadFilePath = "D:\\2023soft\\hahahha.jpg";

    public void down1() {
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest("mylibugu", "2.jpg");
            S3Object s3Object = amazonS3.getObject(getObjectRequest);

            File downloadFile = new File(downloadFilePath);

            InputStream inputStream = s3Object.getObjectContent();

            OutputStream outputStream = new FileOutputStream(downloadFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();

            System.out.println("File downloaded successfully.");
        } catch (AmazonServiceException | IOException e) {
            e.printStackTrace();
            System.out.println("完犊子不行了");
        }
    }


    public void down2() throws IOException {
        File file = new File("D:\\2023soft\\hahahha.jpg");

        S3Object fullObject = amazonS3.getObject(new GetObjectRequest("mylibugu", "2.jpg"));
        String contentType = fullObject.getObjectMetadata().getContentType();
        System.out.println("contentType=============="+contentType);


        displayTextInputStream(fullObject.getObjectContent(),file);

    }

    private static void displayTextInputStream(S3ObjectInputStream objectContent,File downloadFile) throws IOException {
        try (OutputStream outputStream = new FileOutputStream(downloadFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = objectContent.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("下载完成 99999999999999");
        }
    }

}


